#include "centerwidget.h"
#include "ui_centerwidget.h"

CenterWidget::CenterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CenterWidget)
{
    ui->setupUi(this);

    loadStyleSheet("C:/Users/shafl/Desktop/FrameWork/css/img.css");

    m_pTimer = new QTimer(this);

    connect(ui->bntLogin,&QPushButton::clicked,this,&CenterWidget::onLogin);
    connect(ui->bntRegister,&QPushButton::clicked,this,[this](){
        emit selectStackWidget(2);
    });
    connect(m_pTimer,&QTimer::timeout,this,[=](){
        ui->label->clear();
    });


}

CenterWidget::~CenterWidget()
{
    delete ui;

}

void CenterWidget::loadStyleSheet(const QString &CssPath)
{
    QFile file(CssPath);
    if(!file.open(QIODevice::ReadWrite)){
        qDebug() << "open file failed";
        return;
    }
    this->setStyleSheet(file.readAll());
}




void CenterWidget::onLogin()
{
    if (!sqlOperator.openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << sqlOperator.lastError();
        emit sendMessage("数据库连接错误");
        return;
    }
    QList<QVariantMap> users = sqlOperator.selectData("users");
    foreach (const QVariantMap &user, users) {
        UserName = user["name"].toString();
        PassWord = user["passwd"].toString();
        if(ui->lineUserName->text()==UserName){
            if(ui->linePasswd->text()==PassWord){
                ui->label->setText("Welcome "+ui->lineUserName->text()+"!");
                emit sendMessage("登录成功");
                emit selectStackWidget(1);
                return;
            }else{
                emit sendMessage("密码错误");
                ui->linePasswd->clear();
                return;
            }
        }
    }
    emit sendMessage("用户名错误");
    ui->linePasswd->clear();
    ui->lineUserName->clear();
    return;
}

void CenterWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
        {
            // 按下回车键时，触发登录按钮的点击事件
            ui->bntLogin->click();
            event->accept();  // 表示事件已处理
        }
        else
        {
            // 其他按键交给父类处理
            QWidget::keyPressEvent(event);
        }
}
